package com.xcity.tools.ssl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;

public class PfxToJks {

	public static final String PKCS12 = "PKCS12";
	public static final String JKS = "JKS";

	public static final String PFX_KEYSTORE_FILE = "F:/prj_java_svn/city-server/src/main/resource/sock03/214213534020695.pfx";
	public static final String KEYSTORE_PASSWORD = "214213534020695";
	public static final String JKS_KEYSTORE_FILE = "F:/prj_java_svn/city-server/src/main/resource/sock03/server.jks";

	public static void doConvert() {
		try {
			KeyStore inputKeyStore = KeyStore.getInstance(PKCS12);
			FileInputStream fis = new FileInputStream(PFX_KEYSTORE_FILE);
			char[] password = null;
			if ((KEYSTORE_PASSWORD == null)
					|| KEYSTORE_PASSWORD.trim().equals("")) {
				password = null;
			} else {
				password = KEYSTORE_PASSWORD.toCharArray();
			}
			inputKeyStore.load(fis, password);
			fis.close();

			KeyStore outputKeyStore = KeyStore.getInstance(JKS);
			outputKeyStore.load(null, password);
			Enumeration enums = inputKeyStore.aliases();
			while (enums.hasMoreElements()) {
				String keyAlias = (String) enums.nextElement();
				System.out.println("alias=[" + keyAlias + "]");
				if (inputKeyStore.isKeyEntry(keyAlias)) {
					Key key = inputKeyStore.getKey(keyAlias, password);
					Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
					outputKeyStore.setKeyEntry(keyAlias, key, password, certChain);
				}
			}

			FileOutputStream out = new FileOutputStream(JKS_KEYSTORE_FILE);
			outputKeyStore.store(out, password);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		doConvert(); // pfx to jks
	}

}
